﻿using AutoMapper;
using MyTask.Domain.Models;
using MyTask.Infrastructure.Context;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using MyTask.Infrastructure;

namespace MyTask.Domain.Commands.Handlers
{
   public class ShareTaskCommandHandler
    {
        #region Private variable
        //DbContext
        private readonly MyTaskContext _context;
        #endregion
        #region Constructor
        public ShareTaskCommandHandler(MyTaskContext context)
        {
            _context = context;
        }
        #endregion

        #region Public method
        public bool SharedTasks(List<ShareTaskCommand> commands)
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<ShareTaskCommand, ShareTask>());
            IMapper mapper = config.CreateMapper();
            List<ShareTask> shareTasks = mapper.Map<List<ShareTaskCommand>, List<ShareTask>>(commands);
            _context.ShareTasks.AddRange(shareTasks);
            var result = _context.SaveChanges() > 0;
            //send email
            if (result)
            {
                var emailResult = shareTasks.GroupBy(p => p.ToUserId).Select(x =>
                {
                    var toUser = _context.UserInfos.FirstOrDefault(s => s.UserId == x.Key);
                    var fromUserId = x.Select(o => o.FromUserId).FirstOrDefault();
                    var fromUser = _context.UserInfos.FirstOrDefault(s => s.UserId == fromUserId);
                    var taskIdList = x.Select(o => o.TaskInfoId).ToList();
                    var tasks = _context.TaskInfos.Where(s => taskIdList.Contains(s.TaskId)).ToList();
                    StringBuilder mailContent = new StringBuilder();
                    tasks.ForEach(o =>
                    {
                        mailContent.AppendLine($"Task Number:{o.TaskId},Task Name:{o.TaskName},Task Result:{o.TaskResult}");
                    });
                    return new { FromUserEmail = fromUser.Email, ToUserEmail = toUser.Email, EmailContent = mailContent };
                }).ToList();
                emailResult.ForEach(p =>
                {
                    //send email
                    string smtpServer = "www.qq.com";
                    SendEmail.SendMailAsync(smtpServer, true, "qiangxianghui", "123456", "q3938134387", p.FromUserEmail, p.ToUserEmail, "Task Topic", p.EmailContent.ToString());
                });
            }
            return result;
        } 
        #endregion
    }
}
